package main

import (
	"fmt"
	server "kubernates/k8s-stu/httpserver/core"
	"net/http"
	"os"
	"strings"

	"github.com/golang/glog"
)

func main() {
	srv := server.New()
	srv.Use(logRequest)
	srv.Get("/respInfo", respInfo)
	srv.Get("/healthz", healthz)
	srv.Run(":9000")
}

// logRequest 打印请求日志
func logRequest(resp http.ResponseWriter, req *http.Request) {
	glog.Info("客户端IP：", req.RemoteAddr, ";客户端URL：", req.URL.Path)
}

// healthz 心跳检测，状态码为200，body返回OK
func healthz(resp http.ResponseWriter, req *http.Request) {
	resp.WriteHeader(200)
	resp.Write([]byte("OK\n"))
}

// respInfo 将输入请求头和系统环境变量写入到响应头中，且将IP和状态码写入到响应体中
func respInfo(resp http.ResponseWriter, req *http.Request) {

	// 将输入请求头写入到响应头
	for k, v := range req.Header {
		resp.Header().Add(k, strings.Join(v, " "))
	}

	// 将系统环境变量写入响应头
	for _, skv := range os.Environ() {
		kv := strings.Split(skv, "=")
		resp.Header().Add(kv[0], kv[1])
	}

	// 响应体
	resp.Write([]byte("客户端IP：" + req.RemoteAddr + "\n"))
	resp.Write([]byte("状态码：" + fmt.Sprintf("%d", 200)))
}
